// synchronized修饰方法、修饰代码块
class Counter{
    public int count = 0;
    // 修饰方法
    /*public synchronized void add(){
        count++;
    }*/
    // 修饰代码块    快捷键：选中ctrl alt t
    public void add(){
        synchronized (this){
            count++;
        }
    }
}

public class ThreadTest {
    public static void main(String[] args) {
        Counter counter = new Counter();
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 10000; i++) {
                counter.add();
            }
        });

        Thread t2 = new Thread(()->{
            for (int i = 0; i < 10000; i++) {
                counter.add();
            }
        });
        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("每个线程自增10000次，共增到20000次："+counter.count);
    }
}
